//
//  SetUpTableViewController.m
//  Hero
//
//  Created by lanou3g on 16/5/9.
//  Copyright © 2016年 刘永庆. All rights reserved.
//

#import "SetUpTableViewController.h"
#import "YQLoginViewController.h"
#import "OpinionViewController.h"
#import "AboutHeroViewController.h"
@interface SetUpTableViewController ()

@end

@implementation SetUpTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.navigationItem.title = @"个人设置";
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"setupCell"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else if(section == 1){
        return 1;
    }else{
    return 2;
    }
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"setupCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"setupCell"];
    }
    
    if (indexPath.section == 2 && indexPath.row == 1) {
        cell.detailTextLabel.text = @"官方反馈QQ号:1129207509";
        cell.textLabel.text = @"意见反馈";
        cell.imageView.image = [UIImage imageNamed:@"62.png"];
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        cell.textLabel.text = @"切换帐号";
        cell.imageView.image = [UIImage imageNamed:@"64"];

    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.textLabel.text = @"关于掌盟";
        cell.imageView.image = [UIImage imageNamed:@"63"];
    }
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0) {
            NSInteger size = [[SDImageCache sharedImageCache] getSize];
//            float size2 = [self filePath];
            float totalSize = size * 1.0;
            cell.textLabel.text = @"清除缓存";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2fM",totalSize / 1024.0 / 1024.0];
            cell.imageView.image = [UIImage imageNamed:@"60"];
        }
         else{
            cell.textLabel.text = @"夜间模式";
             cell.imageView.image = [UIImage imageNamed:@"61"];
        }
        
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        YQLoginViewController *login = [YQLoginViewController new];
        [self.navigationController pushViewController:login animated:YES];
    }else if (indexPath.section == 2 && indexPath.row == 1) {
        OpinionViewController *opVC = [OpinionViewController new];
        [self.navigationController pushViewController:opVC animated:YES];
    }else if (indexPath.section == 0 && indexPath.row == 0) {
        NSInteger size = [[SDImageCache sharedImageCache] getSize];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"你确定清除%.2f的缓存吗?",size / 1024.0 / 1024.0] preferredStyle:UIAlertControllerStyleAlert] ;
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[SDImageCache sharedImageCache] clearDisk];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                cell.detailTextLabel.text = @"已清除";
            });
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
    else if(indexPath.section == 2 && indexPath.row == 0){
        AboutHeroViewController *about = [AboutHeroViewController new];
        [self.navigationController pushViewController:about animated:YES];
    }
    else if(indexPath.section == 0  && indexPath.row == 1){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定要要切换夜间模式吗?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"夜间模式" object:nil];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nightAction) name:@"夜间模式" object:nil];
    
}
- (void)nightAction
{
     NSLog(@"夜间模式");
}
//-------------------------全部缓存------------
#pragma 清除缓存
- (void)clearCache{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString  *cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask ,  YES )  objectAtIndex : 0 ];
        NSArray *files = [[ NSFileManager defaultManager ]  subpathsAtPath :cachPath];
        for ( NSString *p  in files) {
            NSError *error;
            NSString *path = [cachPath  stringByAppendingPathComponent :p];
            if ([[ NSFileManager defaultManager ]  fileExistsAtPath :path]) {
                [[ NSFileManager defaultManager ]  removeItemAtPath :path  error :&error];
            }
        }
       dispatch_async(dispatch_get_main_queue(), ^{
           [self.tableView reloadData];
       });
    });
}
#pragma 显示缓存大小
//1,单个文件的大小
- (long long) fileSizeAtPath:( NSString *) filePath{
    NSFileManager * manager = [ NSFileManager defaultManager ];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
    }
    return 0 ;
    
}

//2: 遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）

- (float) folderSizeAtPath:( NSString *) folderPath{
    NSFileManager * manager = [ NSFileManager defaultManager ];
    if (![manager fileExistsAtPath :folderPath])
    {
        return 0 ;
    }
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
    }
    return folderSize/( 1024.0 * 1024.0 );
}

// 显示缓存大小

- (float)filePath
{
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    return [ self folderSizeAtPath :cachPath];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
